<template>
    <div class="content">
      <div class="content-head">
        <div class="head-title">
            <span class="title-name">入库小程序</span>
            <span class="title-username">当前用户:{{ userInfo.username }}</span>
        </div>
        <div class="head-button">
            <el-button icon="el-icon-plus" type="info" size="mini" @click="addButton">添加</el-button>
            <el-button icon="el-icon-share" type="primary" plain size="mini" :disabled="selected.length === 0" @click="warehouseEntryBatch">批量入库</el-button>
        </div>
      </div>
      <div class="content-main">
        <el-table :data="tableData" style="width: 100%;" :max-height="tableMaxHeight" @select="tableHandlerSelect" @select-all="tableHandlerSelect" v-loading="tableLoading" class="content-table-item">
            <el-table-column prop="" label="" type="selection" width="" align="center"></el-table-column>
            <el-table-column prop="" label="车间" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <el-select size="mini" v-model="row.workshop" @change="workshopChangeEvent(row,$index)" placeholder="下拉选择车间">
                        <el-option label="机加工" :value="0"></el-option>
                        <el-option label="走心机" :value="1"></el-option>
                        <el-option label="EPC" :value="2"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="" label="工序" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <el-select size="mini" v-model="row.process" placeholder="下拉选择工序">
                        <el-option v-if="row.workshop === 0" label="热处理" value="A"></el-option>
                        <el-option v-if="row.workshop === 0 || row.workshop === 1" label="清洗机" value="B"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="" label="品号" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <!-- remote :remote-method="(query) => materialCodeRemoteMethod(query,row,$index)" -->
                    <el-select size="mini" v-model="row.materialCode" filterable @clear="row.materialList = row.tmp" clearable placeholder="下拉选择产品" @change="materialCodeChange(row,$index)">
                        <el-option v-for="v,i in row.materialList" :label="v" :value="v" :key="i"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="" label="订单" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <el-select size="mini" v-model="row.productOrder" placeholder="下拉选择订单" @change="productOrderChange(row, $index)">
                        <el-option v-for="item,index in row.productOrderList" :label="item.productOrderNumber" :value="item.productOrderNumber" :key="index"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="" label="计划数量" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <el-input :value="row.planNumber" size="mini" disabled placeholder="自动获取"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="" label="订单剩余数量" width="120" align="center">
                <template slot-scope="{ row, $index }">
                    <el-input v-model="row.orderRestNum" size="mini" disabled placeholder="自动获取"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="" label="已入库合格数量" width="120" align="center">
                <template slot-scope="{ row, $index }">
                    <el-input v-model="row.entryStoreQualifiedNum" size="mini" disabled placeholder="自动获取"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="" label="已入库不合格数量" width="135" align="center">
                <template slot-scope="{ row, $index }">
                    <el-input v-model="row.entryStoreUnQualifiedNum" size="mini" disabled placeholder="自动获取"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="" label="领补套数" width="120" align="center">
                <template slot-scope="{ row, $index }">
                    <el-input v-model="row.supplementNum" size="mini" disabled placeholder="自动获取"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="" label="仓库" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <el-select size="mini" v-model="row.warehouseCode" filterable placeholder="下拉选择仓库">
                        <el-option v-for="item,index in storeList" :label="item.warehouseName" :value="item.warehouseCode" :key="index"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="" label="入库日期" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <el-date-picker v-model="row.entryDate" :editable="false" type="date" value-format="yyyy-MM-dd HH:mm:ss" size="mini" placeholder="选择日期时间" class="el-date-picker"></el-date-picker>
                </template>
            </el-table-column>
            <el-table-column prop="" label="申请人" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <el-input v-model="row.username" size="mini" disabled placeholder="自动获取"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="" label="合格数量" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <el-input v-model="row.qualifiedNum" size="mini" :placeholder="row.qualifiedInputPlaceholder ? row.qualifiedInputPlaceholder : '请输入合格数量'" @input="qualifiedNumNumInputEvent(row,$index)"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="" label="不合格数量" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <el-input v-model="row.unQualifiedNum" size="mini" placeholder="请输入不合格数量" @input="unQualifiedNumInputEvent(row,$index)" :disabled="row.rejectOrangeData !== undefined"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="" label="不合格原因" width="200" align="center">
                <template slot-scope="{ row, $index }">
                    <el-select size="mini" v-model="row.unQualifiedReasonList" multiple filterable placeholder="下拉选择原因">
                        <el-option v-for="item,index in reasonList(row)" :label="item" :value="item" :key="index"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="" label="完成数量" width="150" align="center">
                <template slot-scope="{ row, $index }">
                    <el-input :value="row.finishedNum" size="mini" disabled placeholder="自动计算"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="" label="操作" width="100" fixed="right">
                <template slot-scope="{ row, $index }">
                    <el-button v-if="row.rejectOrangeData" type="text" size="mini" @click="warehouseEntry(row,$index)" style="margin-right: 10px;">入库</el-button>
                    <el-popconfirm title="确定删除吗？" @confirm="deleteButton($index,row)">
                        <el-button slot="reference" type="text" size="mini">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
      </div>
    </div>
  </template>

  <script>
  import { reqUserInfo, reqMaterialsInfo,reqProductOrderList,reqUpdateInStockCheck } from "@/api/workOrder.js";
  import { reqMaterialListByGrid, reqEntryWarehouse, reqEntryWarehouseBatch, reqWareHouseInfo, reqFinishedOrderNum, reqSupplementNumByOrderNumber, reqRejectStockListByCurUser,reqDelRejectStockOrder } from "@/api/warehouseEntry.js";
  import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
  import { uniqueId } from "lodash";
  export default {
    name:"warehouseEntry",  //入库小程序
    data() {
      return {
        userInfo:{
            username:"",
            userId:"",
            userPhone:"",
            user:""
        },
        formData:{
            materialListOfA:[],
            materialListOfB:[],
            materialListOfC:[]
        },
        tableData:[],
        selected:[],
        storeList:[],
        tableMaxHeight:450,
        tableLoading:false,
      }
    },
    mounted(){
      //精致环境下进行自动旋转
      //autoOrientation();
      this.getMaterialListByGrid();
      this.getWarehouseList();
      setTimeout(() => {
        this.getUserInfo();
      }, 300);
      this.calculateTableMaxHeight();
      this.getRejectStockListByCurUser();
    },
    methods:{
        //获取当前用户信息
        async getUserInfo () {
            reqUserInfo().then(res => {
                if(res.data.code === 200){
                    this.userInfo.username = res.data.data.nickname;
                    this.userInfo.userId = res.data.data.id;
                    this.userInfo.userPhone = res.data.data.mobile;
                    this.userInfo.user = res.data.data.username;
                }
                console.log("获取当前用户信息",res);
            }).catch(err => {
                this.$message({type:"error",message:"网络异常，用户信息获取失败"});
            })
        },
        getMaterialListByGrid(){
            const grids = [{label:"机加工",grid:143533,category:"materialListOfA"},{label:"走心机",grid:143532,category:"materialListOfB"},{label:"EPC",grid:143534,category:"materialListOfC"}];
            for(let i = 0; i < grids.length; i ++){
                reqMaterialListByGrid(grids[i].grid).then(response => {
                    if(response.data.code === 200){
                        this.formData[grids[i].category] = response.data.data;
                    }
                    console.log('通过车间获取物料信息',response);
                }).catch(error => {
                    this.$message({type:"error",message:"物料信息获取失败"});
                    console.log('通过车间获取物料信息',error);
                })
            }
        },
        addButton(){
            const tmp = {
                randomId:"",
                isSelected:false,
                workshop:"",
                process:"",
                materialCode:"",
                productOrder:"",
                entryDate:"",
                username:"",
                planNumber:"",
                finishedNum:"",
                unQualifiedNum:"",
                qualifiedNum:"",
                materialList:[],
                productOrderList:[],
                tmp:[],
                orderRestNum:0,
                entryStoreQualifiedNum:0,
                entryStoreUnQualifiedNum:0,
                supplementNum:0,  //补领套数
                warehouseCode:"",
                unQualifiedReasonList:[]
            };
            tmp.username = this.userInfo.username;
            tmp.entryDate = this.formatDate(null,0);
            tmp.randomId = uniqueId();
            this.tableData.push(tmp);
        },
        deleteButton(index,row){
            if(row.rejectOrangeData){
                const orderNumber = row.rejectOrangeData.orderNumber;
                reqDelRejectStockOrder([orderNumber]).then(response => {
                    if(response.data.code == 200){
                        this.$notify.success({title: '提示',message: '删除成功'});
                        this.tableData.splice(index,1);
                    }
                }, error => {
                    this.$notify.error({title: '提示',message: '删除失败，请重试'});
                })
                return;
            }
            this.tableData.splice(index,1);
        },
        workshopChangeEvent(row,index){
            const { workshop } = row;
            if(workshop === 0){
                row.materialList = this.formData.materialListOfA;
                row.tmp = this.formData.materialListOfA;
            }
            if(workshop === 1){
                row.materialList = this.formData.materialListOfB;
                row.tmp = this.formData.materialListOfB;
                row.process = "B";
            }
            if(workshop === 2){
                row.materialList = this.formData.materialListOfC;
                row.tmp = this.formData.materialListOfC;
            }
            if(workshop !== 1){
                row.process = "";
            }
            row.materialCode = "";
            row.productOrder = "";
            row.planNumber = "";
            this.clearOrderInfoOfRow(row);
        },
        materialCodeChange(row,index){
            const { materialCode } = row;
            if(materialCode === "") return;
            row.productOrder = "";
            row.productOrderList = [];
            row.planNumber = "";
            reqProductOrderList(materialCode).then(res => {
                if(res.data.code === 200){
                    row.productOrderList = res.data.data.content;
                }
                console.log("通过物料编码/品名查询订单信息",res);
            }).catch(err => {
                this.$message({type:"error",message:"订单信息获取失败"});
            })
            this.clearOrderInfoOfRow(row);
        },
        materialCodeRemoteMethod(query,row,index){
            if(query.trim() === "") {
                row.materialList = row.tmp;
                return;
            }
            reqMaterialsInfo(query).then(response => {
                if(response.data.code === 200 && response.data.data !== null){
                    let { code, id, name } = response.data.data.materialFields;
                    row.materialList = [code];
                }
                if(response.data.code === 200 && response.data.data === null){
                    row.materialList = [];
                }
                console.log('根据物料编号查询物料',response);
            }).catch(error => {
                //this.$message({type:"error",message:"未查询到物料信息"});
                row.materialList = [];
                console.log('error',error);
            })
        },
        async productOrderChange(row,index){
            row.planNumber = "";
            const { productOrderList, productOrder, materialCode } = row;
            const order = productOrderList.find(v => v.productOrderNumber === productOrder);
            const num = order.productOrderMaterials[0].planQuantity;
            row.planNumber = num;
            row.supplementNum = order.productOrderExtendFieldTen || order.productOrderMaterial.productOrderMaterialExtendFieldNine || order.productOrderMaterials[0].productOrderMaterialExtendFieldNine || '';
            if(String(row.supplementNum).length === 0 || Number(row.supplementNum) == 0 || false){
                try {
                    const n = await this.getSupplementNumByOrderNumber(productOrder,materialCode);
                    row.supplementNum = n;
                    console.log('api接口获取到的领补套数:',n);
                } catch (error) {
                    this.$notify.error({title: '提示',message: '请求获取订单领部套数出错,尝试刷新重试'});
                    row.supplementNum = 0;
                }
            }
            try {
                const { entryStoreQualifiedNum, entryStoreUnQualifiedNum } = await this.getFinishedOrderNum(productOrder);
                const restNum = Number(num) - Number(entryStoreUnQualifiedNum) - Number(entryStoreQualifiedNum);
                row.orderRestNum = restNum;
                row.entryStoreQualifiedNum = entryStoreQualifiedNum;
                row.entryStoreUnQualifiedNum = entryStoreUnQualifiedNum;
                //订单剩余申报数量
                row.restReportNum = Number(row.supplementNum) - (Number(row.entryStoreQualifiedNum) + Number(row.entryStoreUnQualifiedNum));
            } catch (error) {
                console.log('请求订单剩余数量出错',error);
            }
            setTimeout(() => {
                const h = this.$createElement;
                this.$msgbox({
                    title: '提示',
                    message: h('div', null, [
                        h('p',{style:{'fontSize':'18px'}},['生产订单号:',h('span',{style:{'color':'red'}},productOrder)]),
                        h('p',{style:{'fontSize':'18px'}},['已领料数量:',h('span',{style:{'color':'red'}},row.supplementNum)]),
                        h('p',{style:{'fontSize':'18px'}},['已报工入库数量:',h('span',{style:{'color':'red'}},Number(row.entryStoreQualifiedNum) + Number(row.entryStoreUnQualifiedNum))]),
                        h('p',{style:{'fontSize':'18px'}},['剩余申报数量:',h('span',{style:{'color':'red'}},Number(row.supplementNum) - (Number(row.entryStoreQualifiedNum) + Number(row.entryStoreUnQualifiedNum)))])
                    ])
                });
            }, 300);
            //row.qualifiedInputPlaceholder = '最大申报数' + row.orderRestNum;
            //this.$forceUpdate();
        },
        qualifiedNumNumInputEvent(row,index){
            const { finishedNum, qualifiedNum, unQualifiedNum, planNumber } = row;
            const regex = /^(?!00)\d+(\.\d{0,1})?$/;
            if (!regex.test(qualifiedNum) && qualifiedNum !== '') {
                row.qualifiedNum = qualifiedNum.slice(0, -1);
                return;
            }
            if(planNumber === "" ){
                row.qualifiedNum = "";
                row.unQualifiedNum = "";
                this.$notify.error({title: '提示',message: '请先选择订单获取计划数量后再填写合格数量'});
                return ;
            }
            const pNum = Number(planNumber);
            const qNum = Number(qualifiedNum);
            const uNum = Number(unQualifiedNum);
            if(qNum + uNum > pNum){
                this.$notify.error({title: '提示',message: '合格数量+不合格数量不能大于计划数量'});
                row.qualifiedNum = qualifiedNum.slice(0, -1);
                return;
            }
            //当前入库数量已超过领补套数剩余数量
            const { supplementNum,entryStoreQualifiedNum,entryStoreUnQualifiedNum } = row;
            const num =  supplementNum - entryStoreUnQualifiedNum - entryStoreQualifiedNum;
            if(qNum + uNum > num){
                this.$notify.error({title: '提示',message: `合格数量+不合格数量不能大于领补套数剩余数量:${supplementNum}(领补套数剩余数量=领补套数-已入库合格数量-已入库不合格数量)`});
                row.qualifiedNum = qualifiedNum.slice(0, -1);
                return;
            }
            row.finishedNum = qNum + uNum;
        },
        unQualifiedNumInputEvent(row,index){
            const { finishedNum, qualifiedNum, unQualifiedNum, planNumber } = row;
            const regex = /^(?!00)\d+(\.\d{0,1})?$/;
            if (!regex.test(unQualifiedNum) && unQualifiedNum !== '') {
                row.unQualifiedNum = unQualifiedNum.slice(0, -1);
                return;
            }
            if(planNumber === "" ){
                row.qualifiedNum = "";
                row.unQualifiedNum = "";
                this.$notify.error({title: '提示',message: '请先选择订单获取计划数量后再填写不合格数量'});
                return ;
            }
            const pNum = Number(planNumber);
            const qNum = Number(qualifiedNum);
            const uNum = Number(unQualifiedNum);
            if(qNum + uNum > pNum){
                this.$notify.error({title: '提示',message: '合格数量+不合格数量不能大于计划数量'});
                row.unQualifiedNum = unQualifiedNum.slice(0, -1);
                return;
            }
            //当前入库数量已超过领补套数剩余数量
            const { supplementNum,entryStoreQualifiedNum,entryStoreUnQualifiedNum } = row;
            const num =  supplementNum - entryStoreUnQualifiedNum - entryStoreQualifiedNum;
            if(qNum + uNum > num){
                this.$notify.error({title: '提示',message:`合格数量+不合格数量不能大于领补套数剩余数量:${supplementNum}(领补套数剩余数量=领补套数-已入库合格数量-已入库不合格数量)`});
                row.unQualifiedNum = unQualifiedNum.slice(0, -1);
                return;
            }
            row.finishedNum = qNum + uNum;
        },
        tableHandlerSelect(selection,row){
            this.selected = selection;
            const list = this.tableData;
            for(let i = 0; i < list.length; i ++){
                list[i].isSelected = false;
            }
            for(let j = 0; j < selection.length; j ++){
                for(let k  = 0; k < list.length; k ++){
                    if(selection[j].randomId == list[k].randomId){
                        list[k].isSelected = true;
                    }
                }
            }
        },
        warehouseEntryBatch(){
            const tmp = this.tableData;
            const tmp_filter = tmp.filter(v => v.isSelected === true );
            if(tmp_filter.length === 0){
                return;
            }
            //存在勾选了驳回的，进行提示
            const f = tmp_filter.filter(f => f.rejectOrangeData);
            if(f.length > 0){
                this.$confirm('勾选入库的数据项中包含了已驳回的数据(已驳回的数据项只能单独进行入库，不能批量入库)', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
                return;
            }
            let checkResult = true;
            let rowIndex = 0;
            let msg = "";
            for(let i = 0; i < tmp.length; i ++){
                const { workshop,process, materialCode, productOrder, orderRestNum,warehouseCode,qualifiedNum,unQualifiedNum,planNumber,finishedNum,isSelected,unQualifiedReasonList } = tmp[i];  //(workshop === 2 && process === "")
                rowIndex = i;
                for(let k in tmp[i]){
                    if((tmp[i][k] === "" || tmp[i][k] === null || tmp[i][k] === undefined) && isSelected){
                        if(k === 'process' && workshop === 2){
                            checkResult = true;
                        } else {
                            checkResult = false;
                            if(k == 'workshop'){
                                msg = '车间不能为空';
                            }
                            if(k == 'process'){
                                msg = '工序不能为空';
                            }
                            if(k == 'materialCode'){
                                msg = '物料编码不能为空';
                            }
                            if(k == 'productOrder'){
                                msg = '订单不能为空';
                            }
                            if(k == 'process'){
                                msg = '工序不能为空';
                            }
                            if(k == 'warehouseCode'){
                                msg = '仓库不能为空';
                            }
                            if(k == 'entryDate'){
                                msg = '入库日期不能为空';
                            }
                            if(k == 'process'){
                                msg = '工序不能为空';
                            }
                            if(k == 'qualifiedNum'){
                                msg = '合格数量不能为空';
                            }
                            if(k == 'unQualifiedNum'){
                                msg = '不合格数量不能为空';
                            }
                            if(k == 'finishedNum'){
                                msg = '请输入合格和不合格数量';
                            }
                            break;
                        }
                    }
                }
                if(!checkResult) break;
                if(Number(finishedNum) > Number(planNumber)){
                    checkResult = false;
                    msg = '完成数量不能大于计划数量';
                    break;
                }
            }
            if(!checkResult){
                this.$notify.error({title: '提示',message: '第' + ( rowIndex + 1 ) + '行填写的数据非法，请检查! ' + `${msg}`});
                return;
            }
            const parameter = new Array();
            for(let j = 0; j < tmp_filter.length; j ++){
                const { materialCode,productOrder,planNumber,finishedNum,qualifiedNum,unQualifiedNum,entryDate,workshop,process,warehouseCode,orderRestNum,supplementNum,entryStoreQualifiedNum,entryStoreUnQualifiedNum,unQualifiedReasonList } = tmp_filter[j];
                const { username,userId,userPhone,user } = this.userInfo;
                const parameterItem = {
                    productCode:materialCode,
                    productNumber:productOrder,
                    plannedQuantity:planNumber,
                    completedQuantity:finishedNum,
                    qualifiedQuantity:qualifiedNum,
                    unqualifiedQuantity:unQualifiedNum,
                    createdDate:entryDate,
                    operatorId:userId,
                    operator:username,
                    operatorPhone:userPhone,
                    username:user,
                    reportRemark:"",
                    warehouseCode,
                    //订单剩余数量
                    //已入库合格数量
                    //已入库不合格数量
                    //补领套数
                    defectReason:unQualifiedReasonList.join(','),
                    origin:tmp_filter[j]
                };
                let remarkStr = "";
                if(workshop === 0){
                    if(process === 'A'){
                        remarkStr = "机加工 热处理";
                    } else if(process === 'B'){
                        remarkStr = "机加工 清洗机";
                    }
                } else if(workshop === 1){
                    remarkStr = "走心机 清洗机";
                } else if(workshop === 2){
                    remarkStr = "EPC";
                }
                parameterItem.reportRemark = remarkStr;
                parameter.push(parameterItem);
            }
            //检测订单中是否存在相同的订单,存在需判断其几次填的合格和不合格数量是否超过其剩余数量
            const isFailReapt = this.checkIsReaptOrder(parameter);
            if(isFailReapt){
              this.$notify.error({title: '提示',message: '存在选择了相同的订单,且累加合格数量和不合格数量超出订单剩余申报数量,请检查!'});
              return ;
            }
            this.$confirm('此操作将进行批量入库, 是否继续?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'})
                .then(() => {
                    reqEntryWarehouseBatch(parameter).then(response => {
                        if(response.data.code === 200){
                            this.$message({type:"success",message:"批量入库成功"});
                            this.tableData = [];
                            this.selected = [];
                        }
                        console.log('批量入库api',response);
                    }).catch(error => {
                        this.$message({type:"error",message:"批量入库失败"});
                        console.log('批量入库api',error);
                    })
                })
                .catch(() => {this.$message({type: 'info',message: '已取消'});
        });
        },
        //格式化时间
        formatDate(val,type){
            let date = null;
            val === null ? date = new Date() : date = new Date(val);
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let h = date.getHours();
            let m = date.getMinutes();
            let s = date.getSeconds();
            if(type === 0){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 1){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day);
            } else if (type === 2){
                return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 3){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
            } else if (type === 4){
            return year + "年" + this.addZero(month) + "月" + this.addZero(day) + "日";
            }
        },
        addZero(val){
            return val > 9 ? val : "0" + val;
        },
        calculateTableMaxHeight(){
            const dom = document.querySelector(".content-main");
            this.$nextTick(() => {
                this.tableMaxHeight = dom.offsetHeight - 10;
            })
        },
        //获取仓库列表信息
        getWarehouseList(){
            reqWareHouseInfo().then(response => {
                if(response.data.code === 200 && response.data.data){
                    const arrayList = response.data.data;
                    //要显示的仓库名
                    const warehouseNameList = ["成品仓","走心机半成品仓","机加工半成品仓"];
                    const tmp = arrayList.map(v => {
                        return {
                            warehouseCode:v.warehouseCode,
                            warehouseId:v.warehouseId,
                            warehouseName:v.warehouseName
                        }
                    })
                    this.storeList = tmp.filter(v => {
                        if(warehouseNameList.includes(v.warehouseName)){
                            return true;
                        }
                        return false;
                    });
                }
                console.log('请求仓库列表信息',response);
            }, error => {
                console.log('请求仓库列表信息',error);
            })
        },
        getFinishedOrderNum(orderNumber){
            return new Promise((resolve,reject) => {
                reqFinishedOrderNum(orderNumber).then(response => {
                    if(response.data.code === 200){
                        resolve(response.data.data);
                    }
                    console.log('请求订单完成数量',response);
                },error => {
                    console.log('请求订单完成数量',error);
                    reject(0);
                })

            })
        },
        //查询订单相关领补套数
        getSupplementNumByOrderNumber(orderNumber,materialCode = null){
            return new Promise((resolve,reject) => {
                reqSupplementNumByOrderNumber(orderNumber).then(response => {
                    if(response.data.code === 200){
                        const list = response.data.data.details;
                        const tmp = list.map(v => {
                            return {materialCode:v['FMaterialId.FNUMBER'],supplementNum:v.FPickMtlQty};
                        })
                        console.log("查询到的领补套数list ===>",tmp);
                        let del = null;
                        if(materialCode && tmp.length !== 0){
                            const a = tmp.find(v => v.materialCode == materialCode);
                            if(a !== undefined){
                                del = a.supplementNum;
                            }
                        } else if(!materialCode && tmp.length === 1){
                            del = tmp[0].supplementNum;
                        }
                        resolve(del);
                    }
                    console.log('获取订单领补套数api',response);
                },error => {
                    reject(error);
                    console.log('获取订单领补套数api',error);
                })
            })
        },
        //获取已驳回的相关数据
        getRejectStockListByCurUser(){
            const _this = this;
            this.tableLoading = true;
            reqRejectStockListByCurUser().then(response => {
                if(response.data.code === 200){
                    const grids = [{label:"机加工",grid:143533,value:0},{label:"走心机",grid:143532,value:1},{label:"EPC",grid:143534,value:2}];
                    const list = response.data.data.content || [];
                    const tmp = list.map(v => {
                        const workshopName = v.remark.split(' ')[0] || v.remarks.split(' ')[0];
                        const processName = (v.remark.split(' ').length > 1 || v.remarks.split(' ').length > 1) ? v.remark.split(' ')[1] || v.remarks.split(' ')[1] : "";
                        const workshop = workshopName.includes('机加工') ? 0 :  workshopName.includes('走心机') ? 1 :  workshopName.includes('EPC') ? 2 : 0;
                        const process = processName != "" ?  (processName.includes('热处理') ? 'A' :  'B') : "";
                        const materialCode = v.materialDetails[0].productCode;
                        const productOrder = v.relateOrderDto.orderNumber;
                        const entryDate = v.createTime;
                        const username = v.applyPerson;
                        const planNumber = v.materialDetails[0].planAmount;
                        const finishedNum = v.materialDetails[0].actualAmount;
                        const warehouseCode = v.warehouseCode;
                        const warehouseName = v.warehouseName;
                        const unQualifiedReasonList = v.ext.fieldTwo || "";
                        console.log(unQualifiedReasonList);
                        return {
                            randomId:"",
                            isSelected:true,
                            workshop:workshop,
                            process:process,
                            materialCode:materialCode,
                            productOrder:productOrder,
                            entryDate:entryDate,
                            username:username,
                            planNumber:'',
                            finishedNum:finishedNum,
                            unQualifiedNum:warehouseName.includes('质检') ? finishedNum : 0,
                            qualifiedNum:warehouseName.includes('质检') ? 0 : finishedNum,
                            materialList:[],
                            productOrderList:[],
                            tmp:[],
                            orderRestNum:'',
                            entryStoreQualifiedNum:'',
                            entryStoreUnQualifiedNum:'',
                            supplementNum:'',  //补领套数
                            warehouseCode:warehouseCode,
                            unQualifiedReasonList:unQualifiedReasonList.split(','),
                            rejectOrangeData:{
                                ...v
                            }
                        }
                    })
                    const requestList = new Array();
                    for(let i = 0; i < tmp.length; i ++){
                        const t = tmp[i];
                        const p1 = reqProductOrderList(t.materialCode).then( response => {
                            t.productOrderList = response.data.data.content;
                            const order = t.productOrderList.find(v => v.productOrderNumber == t.productOrder);
                            if(!order){
                                return;
                            }
                            const num = order.productOrderMaterials[0].planQuantity;
                            t.planNumber = num;
                            t.supplementNum = order.productOrderExtendFieldTen || order.productOrderMaterial.productOrderMaterialExtendFieldNine || order.productOrderMaterials[0].productOrderMaterialExtendFieldNine || '';
                            try {
                                _this.getSupplementNumByOrderNumber(t.productOrder,t.materialCode).then(num => {
                                    t.supplementNum = num;
                                })
                            } catch (error) {
                                console.log('请求领补套数失败',error);
                            }
                            try {
                                _this.getFinishedOrderNum(t.productOrder).then(data => {
                                    const { entryStoreQualifiedNum, entryStoreUnQualifiedNum } = data;
                                    const restNum = Number(num) - Number(entryStoreUnQualifiedNum) - Number(entryStoreQualifiedNum);
                                    t.orderRestNum = restNum;
                                    t.entryStoreQualifiedNum = entryStoreQualifiedNum;
                                    t.entryStoreUnQualifiedNum = entryStoreUnQualifiedNum;
                                    reqMaterialListByGrid(grids.find(g => g.value == t.workshop).grid).then(l => {
                                        t.materialList = l.data.data;
                                    })
                                })
                            } catch (error) {
                                console.log('请求订单已入库合格/不合格数量出错',error);
                            }
                        },error => {
                            console.log('根据物料获取订单列表信息失败',error);
                        })
                        requestList.push(p1);
                    }
                    Promise.all(requestList).then(f => {
                        for(let j = 0; j < tmp.length; j ++){
                            const t = tmp[j];
                            if(t.supplementNum || t.planNumber){
                                _this.tableData.push(t);
                            }
                        }
                        this.tableLoading = false;
                    })
                }
                console.log('获取驳回审核的列表数据api',response);
            },error => {
                this.tableLoading = false;
                console.log('获取驳回审核的列表数据api',error);
            })
        },
        warehouseEntry(row,index){
            const rejectOrangeData = row.rejectOrangeData;
            const { workshop,process,materialCode,productOrder,entryDate,planNumber,finishedNum,unQualifiedNum,qualifiedNum,orderRestNum,entryStoreQualifiedNum,entryStoreUnQualifiedNum,supplementNum,warehouseCode } = row;
            const workshopName = workshop == 0 ? '机加工' : workshop == 1 ? '走心机' : workshop == 2 ? 'EPC' : '';
            const processName = process == 'A' ? '热处理' : '清洗机';
            rejectOrangeData.relateOrders = productOrder;
            rejectOrangeData.remark = workshopName + ' ' + processName;
            rejectOrangeData.remarks = workshopName + ' ' + processName;
            const warehouseInfo = this.storeList.find(v => v.warehouseCode == warehouseCode);
            rejectOrangeData.warehouseCode = warehouseInfo.warehouseCode;
            rejectOrangeData.warehouseId = warehouseInfo.warehouseId;
            rejectOrangeData.warehouseName = warehouseInfo.warehouseName;
            rejectOrangeData.ext.fieldOne = 0;
            rejectOrangeData.materialDetails[0].productCode = materialCode;
            rejectOrangeData.materialDetails[0].planAmount = finishedNum;
            rejectOrangeData.materialDetails[0].actualAmount = finishedNum;
            // rejectOrangeData.qualifiedNum = qualifiedNum;
            // rejectOrangeData.unQualifiedNum = unQualifiedNum;
            rejectOrangeData.planAmount = finishedNum;
            rejectOrangeData.actualAmount = finishedNum;
            this.$confirm('此操作将对驳回的数据重新入库, 是否继续?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(confirm => {
                reqUpdateInStockCheck(rejectOrangeData).then(response => {
                    if(response.data.code === 200){
                        this.$notify.success({title: '提示',message: '入库成功'});
                        this.tableData.splice(index,1);
                    }
                    console.log('驳回数据项单独入库api',response);
                },error => {
                    console.log('驳回数据项单独入库api',error);
                    this.$notify.error({title: '提示',message: '入库失败，请重试'});
                })
            })
        },
        clearOrderInfoOfRow(row){
            if(!row){
                return ;
            }
            row.planNumber = "";
            row.supplementNum = ""
            row.orderRestNum = "";
            row.entryStoreQualifiedNum = "";
            row.entryStoreUnQualifiedNum = "";
        },
        reasonList(item){
            const workshop = item.workshop; //机0 走1 EPC 2
            const list1 = ['换型','换刀','崩刀','断刀','过切','装夹不良','落地件','工废','大小边','其它'];
            const list2 = ['换刀','换型','冷热机','尺寸','铁屑划伤','崩刀','来料不良','工程打样','其它'];
            const list3 = ['打码','压装','焊接','铆接','调机','返修','外协','其它'];
            if(workshop === 0){
                return list1;
            }
            if(workshop === 1){
                return list2;
            }
            if(workshop === 2){
                return list3;
            }
            return [];
        },
        checkIsReaptOrder(parameterList){
          const obj = {},tmp = [];
          for(let i = 0; i < parameterList.length; i ++){
            const { productNumber,origin } = parameterList[i];
            if(!obj[productNumber]){
              obj[productNumber] = 1;
            } else {
              obj[productNumber] += 1;
            }
          }
          Object.entries(obj).forEach(([orderNumber,num]) => {
            if(num > 1) tmp.push(orderNumber);
          });
          if(tmp.length && tmp[0]){
            const orderList = parameterList.filter(v => v.productNumber == tmp[0]);
            if(orderList.length >= 2 && orderList[0]){
              const allNum = orderList.reduce((pre,cur) => {
                return pre + Number(cur.origin.qualifiedNum) + Number(cur.origin.unQualifiedNum);
              },0)
              return allNum > orderList[0].origin.restReportNum;
            }
          }
          return false;
        }
    }
  }
  </script>

<style lang='scss' scoped>
  .content{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;

    .content-head{
      flex: 1;
      display: flex;
      flex-direction: column;
      .head-title{
        flex: 1;
        background: #4095e5;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 3%;
        color: #fff;
      }
      .head-button{
        flex: 1;
        display: flex;
        align-items: center;
        padding: 0 20px;
        box-sizing: border-box;
      }
    }
    .content-main{
      flex: 6;
      margin: 10px 0;
    }
  }
::v-deep .el-table__header th {
  padding: 5px 0; /* 调整上下内边距 */
}
::v-deep .el-radio{
    margin-right:5px;
}
::v-deep .el-radio__label{
    padding-left:3px;
}
::v-deep  .el-date-editor.el-input, .el-date-editor.el-input__inner{
    width:100% !important;
}
</style>
